//店铺数据模块
import {getShopSellerReq, getGoodsListReq,getShopRateReq} from '@/api/shop'
const state = {
  shopData: {},
  goodsList: [], //商品列表
  rateList:[]
}

//getters
//getters
const getters = {
  navList(state) {
    return state.goodsList.map(v => v.name)
  },
  //筛选
  goodRateList(state) {
    return state.rateList.filter(v => {
      return v.score > 3
    })
  },
  badRateList(state) {
    return state.rateList.filter(v => {
      return v.score <= 3
    })
  },
  //筛选出 count>0的食品列表
  filterFoodsList(state) {
    let temp = []
    state.goodsList.forEach(good => {
      good.foods.forEach(food => {
        if (food.count > 0) {
          temp.push(food)
        }
      })
    })
    return temp
  },
  //计算总数量
  filterTotalCount(state, getters) {
    return getters.filterFoodsList.reduce((total, cur) => {
      return total + cur.count
    }, 0)
  },
  //计算总金额
  filterTotalMoney(state, getters) {
    return getters.filterFoodsList.reduce((total, cur) => {
      return total + cur.count * cur.price
    }, 0)
  },
}



const mutations = {
  SET_SHOPINFO(state, data) {
    state.shopData = data
  },
  SET_GOODS_lIST(state, data) {
    state.goodsList = data
  },
  SET_RATE(state, data) {
    state.rateList = data
  },
}

const actions = {
  //获取店铺数据
  A_getShopInfo({commit}) {
    return new Promise(async resolve => {
      let res = await getShopSellerReq()
      //解构数据
      let {data} = res.data
      //数据赋值
      commit('SET_SHOPINFO', data)
      resolve()
    })
  },
  //获取商品列表数据
  A_getGoodsData({commit}) {
    return new Promise(async resolve => {
      //发送请求
      let res = await getGoodsListReq()
      //解构参数
      let {code, data} = res.data
      if(code ===0 ){
        data.forEach(v => {
            v.foods.forEach(subV =>{
              subV.count = 0
            })
        });
      }
      //判断
      if (code === 0) {
        //数据赋值
        commit('SET_GOODS_lIST', data)
        resolve()
      }
    })
  },
  //获取评价
  A_getShopRate({commit}) {
    return new Promise(async resolve => {
      let res = await getShopRateReq()
      let {errno, data} = res.data
      if (errno === 0) {
        commit('SET_RATE', data)
        resolve()
      }
    })
  },
}

// // 获取商品数据
// export const api_shop_ratings = () => {
//   return http({
//     url: "/shop/ratings",
//     method: "get",
//   });
// };

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}
